package main

import (
	"fmt"
	"io"
	"log"
	"strings"
	"sync"
	"time"

	"jdfs2/internal/storage"
)

func main() {
	// 创建append存储实例
	as, err := storage.NewAppendStorage("./test-data", 1024*1024) // 1MB卷大小
	if err != nil {
		log.Fatalf("Failed to create AppendStorage: %v", err)
	}

	fmt.Println("=== Volume级锁保护并发写入示例 ===")

	// 并发写入测试
	const numGoroutines = 5
	const dataSize = 1000

	var wg sync.WaitGroup
	results := make(chan string, numGoroutines)

	// 启动多个goroutine同时写入
	for i := 0; i < numGoroutines; i++ {
		wg.Add(1)
		go func(id int) {
			defer wg.Done()

			data := fmt.Sprintf("concurrent-data-%d-%s", id, strings.Repeat("x", dataSize-20))
			reader := strings.NewReader(data)

			start := time.Now()
			segments, err := as.PutObject("test-bucket", fmt.Sprintf("key-%d", id), reader, int64(len(data)))
			duration := time.Since(start)

			if err != nil {
				results <- fmt.Sprintf("Goroutine %d: 写入失败 - %v", id, err)
				return
			}

			// 验证写入的数据
			readCloser, err := as.GetObject("test-bucket", fmt.Sprintf("key-%d", id), segments)
			if err != nil {
				results <- fmt.Sprintf("Goroutine %d: 读取失败 - %v", id, err)
				return
			}

			readData, err := io.ReadAll(readCloser)
			readCloser.Close()
			if err != nil {
				results <- fmt.Sprintf("Goroutine %d: 读取数据失败 - %v", id, err)
				return
			}

			if string(readData) != data {
				results <- fmt.Sprintf("Goroutine %d: 数据不匹配", id)
				return
			}

			results <- fmt.Sprintf("Goroutine %d: 成功写入%d字节，耗时%v，使用%d个片段",
				id, len(data), duration, len(segments))
		}(i)
	}

	// 等待所有goroutine完成
	wg.Wait()
	close(results)

	// 显示结果
	fmt.Println("\n=== 并发写入结果 ===")
	for result := range results {
		fmt.Println(result)
	}

	// 显示卷信息
	fmt.Println("\n=== 卷使用情况 ===")
	volumes := as.ListVolumes()
	for _, volume := range volumes {
		fmt.Printf("卷 %d: 已使用 %d/%d 字节 (%.1f%%), 状态: %v\n",
			volume.ID, volume.Used, volume.Size,
			float64(volume.Used)/float64(volume.Size)*100,
			map[bool]string{true: "活跃", false: "非活跃"}[volume.IsActive])
	}

	// 清理锁
	fmt.Println("\n=== 清理非活跃卷锁 ===")
	as.CleanupInactiveVolumeLocks()
	fmt.Println("锁清理完成")

	fmt.Println("\n=== 示例完成 ===")
}
